package com.orange.cetback.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.orange.cetback.common.constant.MessageConstant;
import com.orange.cetback.common.context.BaseContext;
import com.orange.cetback.common.exception.LoginFailedException;
import com.orange.cetback.common.properties.WeChatProperties;
import com.orange.cetback.common.utils.HttpClientUtil;
import com.orange.cetback.common.vo.PageResult;
import com.orange.cetback.pojo.dto.UserDTO;
import com.orange.cetback.pojo.dto.UserLoginDTO;
import com.orange.cetback.pojo.entity.User;
import com.orange.cetback.mapper.UserMapper;
import com.orange.cetback.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户信息 服务实现类
 * </p>
 *
 * @author chenenjun
 * @since 2025-02-11
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    //微信服务接口地址
    public static final String WX_LOGIN="https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Override
    public List<User> getUserList() {
        return this.baseMapper.selectList(null);
    }

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        String openid = userLoginDTO.getOpenid() == null ? getOpenid(userLoginDTO.getCode()) : userLoginDTO.getOpenid();
        //判断openid是否为空，如果为空表示登录失败，抛出业务异常
        if(openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getOpenid, openid);
        User user = this.baseMapper.selectOne(wrapper);
        //如果是新用户，自动完成注册
        if(user == null){
            user=User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            this.baseMapper.insert(user);
        }
        //返回这个用户对象
        return user;
    }

    @Override
    public void switchLevel(String studyLevel) {
        this.baseMapper.updateById(User.builder().id(BaseContext.getCurrentId()).studyLevel(studyLevel).build());
    }

    @Override
    public PageResult<User> pageQuery(UserDTO userDTO) {
        Page<User> page = new Page<>(userDTO.getPageNum(), userDTO.getPageSize());
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(userDTO.getName() != null, User::getName, userDTO.getName());
        //将openid设置为空
        queryWrapper.select(User::getId, User::getName, User::getPhone, User::getSex, User::getIdNumber, User::getAvatar, User::getCreateTime, User::getStudyLevel);
        this.baseMapper.selectPage(page, queryWrapper);
        return new PageResult<>(page.getTotal(), page.getRecords());
    }

    /**
     * 更新积分
     * @param integral
     */
    @Override
    public void UpdateIntegral(Integer integral) {
        //更新积分
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(User::getId, BaseContext.getCurrentId())
                .setSql("integral=integral+" + integral);
        this.baseMapper.update(null, wrapper);
    }

    /**
     * 调用微信服务器接口，获取当前微信用户的openid
     * @param code
     * @return
     */
    private String getOpenid(String code){
        //调用微信服务器接口，获取当前微信用户的openid
        Map<String,String> map =new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");

        return openid;
    }
}
